from django.http import HttpResponse
from rest_framework import viewsets, mixins, status
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from core.tools.SerializerAPIView import SerializerAPIView
from .serializers import YLPaySerializers, MiniSerializers, WeChatOrdeSerializer
from apps.czb.models import Orders as CzbOrders
from apps.coffee.models import CoffeeOrder
from apps.supply_order.models import SupplyOrder, WomaiChildOrder
from rest_framework.response import Response
from .client import YLClient, YLAppPay, yl_app_pay
from .models import YLPayRecord
from finance_c2c.local_settings import ONLINE

yl_client = YLClient()


# 获取银联支付链接
class YLPayAPIView(SerializerAPIView):
    """
    获取银联支付链接
        post: 获取银联支付链接
    """
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = YLPaySerializers

    def post(self, request):
        user = request.user
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            pay_order_model = serializer.validated_data.get("pay_order_model")
            s_order_pk = serializer.validated_data.get("supply_id")
            redirect_url = serializer.validated_data.get("redirect_url")
            pay_type = serializer.validated_data.get("pay_type")
            if pay_order_model == "czb":
                czb_order_instance = CzbOrders.objects.get(id=s_order_pk)
                totalAmount = int(czb_order_instance.payment * 100)
                srcReserve = "czb"
                orderDesc = ""
                if not ONLINE:
                    totalAmount = 2
                if pay_type == 3:
                    response = yl_app_pay.app_pay(redirect_url, totalAmount, srcReserve="czb")
                    merOrderId = response.get("merOrderId")
                    pay_url = response.get("qrCode")
                else:
                    pay_url, merOrderId = YLClient().pay(srcReserve, orderDesc, totalAmount, redirect_url,
                                                         pay_type=pay_type)
                if pay_type == 1:  # 银联公众号支付
                    czb_order_instance.update_pay_info(merOrderId, pay_type=4)
                else:
                    czb_order_instance.update_pay_info(merOrderId, pay_type=pay_type)
            elif pay_order_model == "coffee":
                coffee_order_instance = CoffeeOrder.objects.get(out_trade_no=s_order_pk)
                totalAmount = coffee_order_instance.payment
                merOrderId = coffee_order_instance.out_trade_no
                srcReserve = "coffee"
                orderDesc = ""
                if not ONLINE:
                    totalAmount = 2
                if pay_type == 3:
                    response = yl_app_pay.app_pay(redirect_url, totalAmount, srcReserve="coffee", merOrderId=merOrderId)
                    pay_url = response.get("qrCode")
                else:
                    pay_url, merOrderId = YLClient().pay(srcReserve, orderDesc, totalAmount, redirect_url,
                                                         pay_type=pay_type, merOrderId=merOrderId)

            else:
                s_order = SupplyOrder.objects.get(id=s_order_pk)
                totalAmount = s_order.payment
                srcReserve = ""
                orderDesc = ""
                if not ONLINE:
                    totalAmount = 2
                if pay_type == 3:
                    response = yl_app_pay.app_pay(redirect_url, totalAmount, srcReserve="czb")
                    merOrderId = response.get("merOrderId")
                    pay_url = response.get("qrCode")
                    s_order.out_trade_no = merOrderId
                    s_order.save()
                else:
                    pay_url, merOrderId = YLClient().pay(srcReserve, orderDesc, totalAmount, redirect_url,
                                                         pay_type=pay_type)
                    s_order.out_trade_no = merOrderId
                    s_order.save()
            YLPayRecord.objects.create_record(totalAmount, merOrderId, srcReserve=srcReserve, pay_type=pay_type)
            response = {"mweb_url": pay_url}
            return Response(response, status=status.HTTP_200_OK)


class NotifyUrl(mixins.CreateModelMixin, viewsets.GenericViewSet):
    """
    接收通联异步退款通知
    """
    pass


# 退款
class RefundViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    """
    """
    pass


# 银商支付通知公众号支付
def notify(request):
    if request.method == "POST":
        data = request.POST
        print(data, "yinlian pay notify")
        merOrderId = data.get("merOrderId")
        response = yl_client.query(merOrderId)
        instance = YLPayRecord.objects.get(out_trade_no=merOrderId)
        notifyId = data.get("notifyId")
        response["notifyId"] = notifyId
        instance.update_record(response)
        srcReserve = response.get("srcReserve")
        srcReverse = response.get("srcReverse")
        if response.get("status") == "TRADE_SUCCESS":
            if srcReserve == "czb" or srcReverse == "czb":
                czb_orders = CzbOrders.objects.get(out_trade_no=merOrderId)
                czb_orders.update_pay_result(1, pay_type=4)  # 1:支付成功
                czb_orders.save()
            elif srcReserve == "coffee" or srcReverse == "coffee":
                coffee_order_instance = CoffeeOrder.objects.get(out_trade_no=merOrderId)
                coffee_order_instance.update_result()
            else:
                supply_orders = SupplyOrder.objects.get(out_trade_no=merOrderId)
                supply_orders.update_trade_type_fixed(pay_type=4)  # 更新订单
                WomaiChildOrder.objects.update_pay_result(supply_orders, pay_type="yl")  # 通过支付结果更新其他数据
            return HttpResponse("SUCCESS")
        else:
            return HttpResponse("SUCCESS")
    else:
        return HttpResponse("hello")


# 银商支付通知APP支付
def app_notify(request):
    if request.method == "POST":
        data = request.POST
        print(data, "app yinlian pay notify")
        merOrderId = data.get("merOrderId")
        response = yl_app_pay.search(merOrderId)
        instance = YLPayRecord.objects.get(out_trade_no=merOrderId)
        notifyId = data.get("notifyId")
        response["notifyId"] = notifyId
        instance.update_record(response)
        srcReserve = response.get("srcReserve")
        srcReverse = response.get("srcReverse")
        if response.get("status") == "TRADE_SUCCESS":
            if srcReserve == "czb" or srcReverse == "czb":
                czb_orders = CzbOrders.objects.get(out_trade_no=merOrderId)
                czb_orders.update_pay_result(1, pay_type=7)  # 1:支付成功
                czb_orders.save()
            else:
                supply_orders = SupplyOrder.objects.get(out_trade_no=merOrderId)
                supply_orders.update_trade_type_fixed(pay_type=7)  # 更新订单
                WomaiChildOrder.objects.update_pay_result(supply_orders, pay_type="yl")  # 通过支付结果更新其他数据
            return HttpResponse("SUCCESS")
        else:
            return HttpResponse("SUCCESS")
    else:
        return HttpResponse("hello")


# app支付
class AppPay(SerializerAPIView):
    def get(self, request):
        response = YLAppPay().app_pay("https://c2c-uat.kalaibao.com/c2c/", "1", "czb")
        return Response(response)


class MiniPay(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = MiniSerializers
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        response = self.perform_create(serializer)
        return Response(response, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        return serializer.save()


def mini_notify(request):
    if request.method == "POST":
        data = request.POST
        print(data, "银联小程序支付通知参数")
        if data.get("status") == "TRADE_SUCCESS":
            return HttpResponse("FAILED")
        else:
            return HttpResponse("SUCCESS")
    else:
        return HttpResponse("hello")


# 银联公众号支付(coffee) 返回链接
class YlWxPayAPIView(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = WeChatOrdeSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        mweb_url, instance = self.perform_create(serializer)
        data = dict()
        data["out_trade_no"] = instance.out_trade_no
        data["mweb_url"] = mweb_url
        return Response(data, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        return serializer.save()

